package com.example.contacter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyHolder> {
    List<Person> mDatas;

    public ContactAdapter(List<Person> datas) {
        mDatas = datas;
    }

    @NonNull
    @Override
    public ContactAdapter.MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contact, null);
        return new MyHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull ContactAdapter.MyHolder holder, int position) {
        String mLetter = mDatas.get(position).getPinyin().substring(0, 1);
        if (position == 0) {
            holder.tvZimu.setVisibility(View.VISIBLE);
        } else {
            if (mLetter.equals(mDatas.get(position - 1).getPinyin().substring(0, 1))) {
                holder.tvZimu.setVisibility(View.GONE);
            } else {
                holder.tvZimu.setVisibility(View.VISIBLE);
            }
        }

        holder.tvZimu.setText(mLetter);
        holder.tvName.setText(mDatas.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {
        TextView tvZimu, tvName;

        MyHolder(@NonNull View itemView) {
            super(itemView);
            tvZimu = itemView.findViewById(R.id.item_contact_letter);
            tvName = itemView.findViewById(R.id.item_contact_name);
        }
    }
}